<template>
  <div class="material-template-container">
    <div class="header-actions">
      <el-button 
        type="primary" 
        icon="el-icon-plus" 
        @click="handleAdd"
        style="background-color: #803f7d; border-color: #803f7d;">
        添加材料模板
      </el-button>
      
      <el-button 
        type="danger" 
        icon="el-icon-delete" 
        :disabled="selectedIds.length === 0"
        @click="handleBatchDelete">
        批量删除
      </el-button>
       
      <!-- <el-button 
        type="success" 
        icon="el-icon-connection" 
        @click="testConnection">
        测试连接
      </el-button> -->
      
      <!-- <el-button 
        type="warning" 
        icon="el-icon-mobile-phone" 
        @click="testMiniappApi">
        测试小程序接口
      </el-button> -->
      
      <!-- <el-button 
        type="info" 
        icon="el-icon-search" 
        @click="checkProductMaterials">
        检查产品材料
      </el-button> -->
      
      <!-- <el-button 
        type="primary" 
        icon="el-icon-upload" 
        @click="testUploadDir">
        测试上传目录
      </el-button> -->
    </div>

    <!-- 搜索区域 -->
    <div class="search-area">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="材料名称">
          <el-input 
            v-model="searchForm.materialName" 
            placeholder="请输入材料名称"
            clearable
            @keyup.enter.native="handleSearch">
          </el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.isEnabled" placeholder="请选择状态" clearable>
            <el-option label="启用" :value="1"></el-option>
            <el-option label="禁用" :value="0"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 表格区域 -->
    <el-table 
      :data="tableData" 
      :loading="loading"
      @selection-change="handleSelectionChange"
      style="width: 100%">
      
      <el-table-column type="selection" width="55"></el-table-column>
      
      <el-table-column prop="id" label="ID" width="80"></el-table-column>
      
      <el-table-column prop="materialName" label="材料名称" min-width="120"></el-table-column>
      
      <el-table-column label="材料图标" width="100">
        <template slot-scope="scope">
          <img 
            v-if="scope.row.materialIconUrl" 
            :src="scope.row.materialIconUrl" 
            class="material-icon-preview"
            @error="handleImageError">
          <span v-else class="no-image">无图片</span>
        </template>
      </el-table-column>
      
      <el-table-column prop="description" label="描述" min-width="150" show-overflow-tooltip></el-table-column>
      
      <el-table-column prop="sortOrder" label="排序" width="80"></el-table-column>
      
      <el-table-column label="状态" width="80">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.isEnabled"
            :active-value="1"
            :inactive-value="0"
            @change="handleStatusChange(scope.row)">
          </el-switch>
        </template>
      </el-table-column>
      
      <el-table-column prop="createTime" label="创建时间" width="160">
        <template slot-scope="scope">
          {{ formatTime(scope.row.createTime) }}
        </template>
      </el-table-column>
      
      <el-table-column label="操作" width="180" fixed="right">
        <template slot-scope="scope">
          <el-button size="mini" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button size="mini" type="danger" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </div>

    <!-- 添加/编辑弹窗 -->
    <el-dialog 
      :title="dialogTitle" 
      :visible.sync="dialogVisible" 
      width="600px"
      @close="handleDialogClose">
      
      <el-form 
        ref="formRef" 
        :model="formData" 
        :rules="formRules" 
        label-width="100px">
        
        <el-form-item label="材料名称" prop="materialName">
          <el-input v-model="formData.materialName" placeholder="请输入材料名称"></el-input>
        </el-form-item>
        
        <el-form-item label="材料图标" prop="materialIconUrl">
          <el-upload
            class="icon-uploader"
            :action="uploadAction"
            :show-file-list="false"
            :on-success="handleIconSuccess"
            :before-upload="beforeIconUpload"
            :headers="uploadHeaders">
            <img v-if="formData.materialIconUrl" :src="formData.materialIconUrl" class="icon-preview">
            <i v-else class="el-icon-plus icon-uploader-icon"></i>
          </el-upload>
          <div class="upload-tip">建议尺寸：64x64px，支持jpg、png格式，大小不超过2MB</div>
        </el-form-item>
        
        <el-form-item label="描述">
          <el-input 
            v-model="formData.description" 
            type="textarea" 
            :rows="3"
            placeholder="请输入材料描述">
          </el-input>
        </el-form-item>
        
        <el-form-item label="排序序号" prop="sortOrder">
          <el-input-number 
            v-model="formData.sortOrder" 
            :min="0" 
            :max="999"
            placeholder="请输入排序序号">
          </el-input-number>
        </el-form-item>
        
        <el-form-item label="状态">
          <el-radio-group v-model="formData.isEnabled">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="submitting" @click="handleSubmit">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import axios from '@/utils/request'
import dayjs from 'dayjs'

export default {
  name: 'MaterialTemplateManagement',
  data() {
    return {
      // 表格数据
      tableData: [],
      loading: false,
      selectedIds: [],
      
      // 分页
      currentPage: 1,
      pageSize: 10,
      total: 0,
      
      // 搜索
      searchForm: {
        materialName: '',
        isEnabled: null
      },
      
      // 弹窗
      dialogVisible: false,
      isEditMode: false,
      submitting: false,
      
      // 表单
      formData: {
        id: null,
        materialName: '',
        materialIconUrl: '',
        description: '',
        sortOrder: 0,
        isEnabled: 1
      },
      
      formRules: {
        materialName: [
          { required: true, message: '请输入材料名称', trigger: 'blur' },
          { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
        ],
        sortOrder: [
          { required: true, message: '请输入排序序号', trigger: 'blur' }
        ]
      },
      
      // 上传
      uploadAction: 'http://localhost:8080/admin/material-template/upload-icon',
      uploadHeaders: {
        'Authorization': 'Bearer ' + (localStorage.getItem('token') || '')
      }
    }
  },
  
  computed: {
    dialogTitle() {
      return this.isEditMode ? '编辑材料模板' : '添加材料模板'
    }
  },
  
  mounted() {
    console.log('MaterialTemplateManagement 组件已挂载');
    this.fetchData()
  },
  
  methods: {
    // 获取数据
    async fetchData() {
      console.log('开始获取材料模板数据...');
      this.loading = true
      try {
        const res = await axios.get('/admin/material-template/page', {
          params: {
            page: this.currentPage,
            pageSize: this.pageSize,
            ...this.searchForm
          }
        })
        
        console.log('获取数据成功:', res);
        
        // 根据其他页面的数据结构，应该是 res.data.records 和 res.data.total
        if (res.code === 1 && res.data) {
          this.tableData = res.data.records || []
          this.total = res.data.total || 0
          
          console.log('解析后的数据:', {
            tableData: this.tableData,
            total: this.total,
            dataLength: this.tableData.length
          });
          
          if (this.tableData.length === 0) {
            this.$message.info('未找到匹配的数据')
          }
        } else {
          this.tableData = []
          this.total = 0
          this.$message.warning(res.msg || '获取数据失败')
        }
      } catch (error) {
        console.error('获取数据失败:', error);
        this.$message.error('获取数据失败: ' + (error.message || '未知错误'))
      } finally {
        this.loading = false
      }
    },
    
    // 搜索
    handleSearch() {
      this.currentPage = 1
      this.fetchData()
    },
    
    // 重置搜索
    handleReset() {
      this.searchForm = {
        materialName: '',
        isEnabled: null
      }
      this.handleSearch()
    },
    
    // 添加
    handleAdd() {
      this.isEditMode = false
      this.formData = {
        id: null,
        materialName: '',
        materialIconUrl: '',
        description: '',
        sortOrder: 0,
        isEnabled: 1
      }
      this.dialogVisible = true
      this.$nextTick(() => {
        this.$refs.formRef?.clearValidate()
      })
    },
    
    // 编辑
    handleEdit(row) {
      this.isEditMode = true
      this.formData = { ...row }
      this.dialogVisible = true
      this.$nextTick(() => {
        this.$refs.formRef?.clearValidate()
      })
    },
    
    // 删除
    async handleDelete(row) {
      try {
        await this.$confirm(`确定删除材料模板"${row.materialName}"吗？`, '提示', {
          type: 'warning'
        })
        
        await axios.delete(`/admin/material-template/${row.id}`)
        this.$message.success('删除成功')
        this.fetchData()
      } catch (error) {
        if (error !== 'cancel') {
          this.$message.error('删除失败')
        }
      }
    },
    
    // 批量删除
    async handleBatchDelete() {
      try {
        await this.$confirm(`确定删除选中的 ${this.selectedIds.length} 个材料模板吗？`, '提示', {
          type: 'warning'
        })
        
        await axios.delete('/admin/material-template/batch', {
          data: this.selectedIds
        })
        
        this.$message.success('批量删除成功')
        this.selectedIds = []
        this.fetchData()
      } catch (error) {
        if (error !== 'cancel') {
          this.$message.error('批量删除失败')
        }
      }
    },
    
    // 状态切换
    async handleStatusChange(row) {
      try {
        await axios.put(`/admin/material-template/status/${row.id}`, null, {
          params: { status: row.isEnabled }
        })
        this.$message.success('状态更新成功')
      } catch (error) {
        // 恢复原状态
        row.isEnabled = row.isEnabled === 1 ? 0 : 1
        this.$message.error('状态更新失败')
      }
    },
    
    // 提交表单
    async handleSubmit() {
      try {
        await this.$refs.formRef.validate()
        this.submitting = true
        
        console.log('提交表单数据:', this.formData);
        
        if (this.isEditMode) {
          const res = await axios.put('/admin/material-template', this.formData)
          console.log('修改响应:', res);
          this.$message.success('修改成功')
        } else {
          const res = await axios.post('/admin/material-template/add', this.formData)
          console.log('添加响应:', res);
          this.$message.success('添加成功')
        }
        
        this.dialogVisible = false
        this.fetchData()
      } catch (error) {
        console.error('提交失败:', error);
        if (error.message) {
          this.$message.error('提交失败: ' + (error.message || '未知错误'))
        }
      } finally {
        this.submitting = false
      }
    },
    
    // 图标上传成功
    handleIconSuccess(res) {
      console.log('图标上传响应:', res);
      if (res.code === 1) {
        this.formData.materialIconUrl = res.data
        console.log('设置图标URL:', res.data);
        console.log('当前表单数据:', this.formData);
        this.$message.success('图标上传成功')
      } else {
        console.error('图标上传失败:', res);
        this.$message.error('图标上传失败: ' + (res.msg || '未知错误'))
      }
    },
    
    // 图标上传前验证
    beforeIconUpload(file) {
      const isImage = file.type.startsWith('image/')
      const isLt2M = file.size / 1024 / 1024 < 2
      
      if (!isImage) {
        this.$message.error('只能上传图片文件!')
      }
      if (!isLt2M) {
        this.$message.error('图片大小不能超过2MB!')
      }
      return isImage && isLt2M
    },
    
    // 选择变化
    handleSelectionChange(selection) {
      this.selectedIds = selection.map(item => item.id)
    },
    
    // 分页
    handleSizeChange(val) {
      this.pageSize = val
      this.currentPage = 1
      this.fetchData()
    },
    
    handleCurrentChange(val) {
      this.currentPage = val
      this.fetchData()
    },
    
    // 弹窗关闭
    handleDialogClose() {
      this.$refs.formRef?.resetFields()
    },
    
    // 图片加载错误
    handleImageError(e) {
      console.log('图片加载失败:', e.target.src);
      // 避免无限循环，只处理一次
      if (!e.target.dataset.errorHandled) {
        e.target.dataset.errorHandled = 'true';
        // 隐藏图片，显示默认文本
        e.target.style.display = 'none';
        // 在父元素中添加默认提示
        const parent = e.target.parentElement;
        if (parent && !parent.querySelector('.error-placeholder')) {
          const placeholder = document.createElement('span');
          placeholder.className = 'error-placeholder no-image';
          placeholder.textContent = '无图片';
          parent.appendChild(placeholder);
        }
      }
    },
    
    // 测试连接
    async testConnection() {
      try {
        console.log('测试后端连接...');
        const res = await axios.get('/admin/material-template/test');
        console.log('测试连接成功:', res);
        this.$message.success('后端连接正常: ' + res.data);
      } catch (error) {
        console.error('测试连接失败:', error);
        this.$message.error('后端连接失败: ' + (error.message || '未知错误'));
      }
    },
    
    // 测试小程序接口
    async testMiniappApi() {
      try {
        console.log('测试小程序接口...');
        const res = await axios.get('/admin/material-template/miniapp/list');
        console.log('小程序接口响应:', res);
        if (res.code === 1) {
          this.$message.success(`小程序接口正常，返回${res.data.length}条数据`);
          console.log('小程序接口数据:', res.data);
        } else {
          this.$message.warning('小程序接口返回异常: ' + (res.msg || '未知错误'));
        }
      } catch (error) {
        console.error('小程序接口测试失败:', error);
        this.$message.error('小程序接口测试失败: ' + (error.message || '未知错误'));
      }
    },
    
    // 检查产品材料
    async checkProductMaterials() {
      try {
        console.log('检查产品37的材料要求...');
        const res = await axios.get('/admin/visa-material-requirement/miniapp/product-id/37');
        console.log('产品37材料要求完整数据:', res);
        if (res.code === 1) {
          const materials = res.data.map(item => item.materialName).filter((name, index, arr) => arr.indexOf(name) === index);
          console.log('产品37的材料列表:', materials);
          
          // 显示详细的材料要求数据
          console.log('产品37材料要求详细数据:');
          res.data.forEach((item, index) => {
            console.log(`${index + 1}. ID: ${item.id}, 材料名称: ${item.materialName}, 用户类型: ${item.userType || '无'}`);
          });
          
          this.$message.info(`产品37包含材料: ${materials.join(', ')}`);
          
          // 检查是否有"出生证明"
          if (materials.includes('出生证明')) {
            this.$confirm('发现产品37中有"出生证明"材料，但材料模板中可能是"婚姻状况"，是否要修复这个数据不一致问题？', '数据不一致', {
              confirmButtonText: '修复',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              this.fixMaterialInconsistency();
            });
          }
          
          // 同时检查材料模板数据
          console.log('对比检查材料模板数据...');
          const templateRes = await axios.get('/admin/material-template/miniapp/list');
          if (templateRes.code === 1) {
            const templateNames = templateRes.data.map(t => t.materialName);
            console.log('材料模板名称列表:', templateNames);
            
            // 找出不匹配的材料
            const unmatchedMaterials = materials.filter(m => !templateNames.includes(m));
            const unmatchedTemplates = templateNames.filter(t => !materials.includes(t));
            
            if (unmatchedMaterials.length > 0) {
              console.warn('产品材料中没有对应模板的:', unmatchedMaterials);
            }
            if (unmatchedTemplates.length > 0) {
              console.warn('材料模板中没有对应产品材料的:', unmatchedTemplates);
            }
          }
        }
      } catch (error) {
        console.error('检查产品材料失败:', error);
        this.$message.error('检查产品材料失败: ' + (error.message || '未知错误'));
      }
    },
    
    // 修复材料不一致问题
    async fixMaterialInconsistency() {
      try {
        // 这里可以调用后端接口来修复数据
        this.$message.info('数据修复功能需要后端支持，请手动在数据库中将"出生证明"改为"婚姻状况"');
      } catch (error) {
        console.error('修复材料不一致失败:', error);
        this.$message.error('修复失败: ' + (error.message || '未知错误'));
      }
    },
    
    // 测试上传目录
    async testUploadDir() {
      try {
        console.log('测试上传目录...');
        const res = await axios.get('/admin/material-template/upload-test');
        console.log('上传目录测试结果:', res);
        if (res.code === 1) {
          this.$message.success('上传目录测试成功');
          console.log('上传目录信息:', res.data);
        } else {
          this.$message.warning('上传目录测试异常: ' + (res.msg || '未知错误'));
        }
      } catch (error) {
        console.error('上传目录测试失败:', error);
        this.$message.error('上传目录测试失败: ' + (error.message || '未知错误'));
      }
    },
    
    // 时间格式化
    formatTime(time) {
      return time ? dayjs(time).format('YYYY-MM-DD HH:mm') : '-'
    }
  }
}
</script>

<style scoped>
.material-template-container {
  padding: 20px;
}

.header-actions {
  margin-bottom: 20px;
}

.search-area {
  background: #fff;
  padding: 20px;
  margin-bottom: 20px;
  border-radius: 4px;
}

.search-form {
  margin-bottom: 0;
}

.material-icon-preview {
  width: 40px;
  height: 40px;
  object-fit: cover;
  border-radius: 4px;
}

.no-image, .error-placeholder {
  color: #999;
  font-size: 12px;
  text-align: center;
  display: block;
  line-height: 40px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

.icon-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 80px;
  height: 80px;
}

.icon-uploader .el-upload:hover {
  border-color: #409EFF;
}

.icon-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 80px;
  height: 80px;
  line-height: 80px;
  text-align: center;
}

.icon-preview {
  width: 80px;
  height: 80px;
  display: block;
  object-fit: cover;
}

.upload-tip {
  font-size: 12px;
  color: #999;
  margin-top: 5px;
}
</style>
